Ext.define('YX.core.RolePermission', {
	 extend : 'Ext.panel.Panel',
	 layout : {
	  type : 'hbox',
	  align : 'stretch'
	 },
	 cmbFunSide : null,
	 treePermission : null,
	 gridFun : null,
	 gridFunCtl : null,
	 gridRole : null,
	 cmbOrgCode : null,
	 txtRoleCode : null,
	 txtRoleName : null,
	 cmbStatus : null,
	 btnAddSibling : null,
	 btnAddChild : null,
	 btnRemove : null,
	 btnRefresh : null,
	 btnSaveRole : null,
	 btnSavePermission : null,
	 btnSaveControl : null,
	 initComponent : function() {
	  //权限类型
	  this.cmbFunSide = Ext.create('Ext.form.field.ComboBox', {
		   fieldLabel : T.label.clientSide,
		   editable : false,
		   name : 'funSide',
		   labelWidth : 60,
		   valueField : 'value',
		   displayField : 'text',
		   value : 'U',
		   store : Ext.create('Ext.data.ArrayStore', {
		      fields : ['value', 'text'],
		      data : [['U', T.label.func], ['O', T.label.operate], ['C', T.label.chart]]
		     }),
		   listeners : {
		    scope : this,
		    select : this.onCmbFunSideSelect
		   }
	    });

	  //权限树
	  this.treePermission = Ext.create('Ext.tree.Panel', {
		   title : T.label.permission,
		   flex : 1,
		   rootVisible : true,
		   root : {
		    text : T.label.permission
		   },
		   store : Ext.create('Ext.data.TreeStore', {
		      fields : ['roleOrgCode', 'roleCode', 'funCode', 'parentFunCode', 'asmName', 'asmFile', 'funType', 'funSide',
		        'iconPath', 'text'],
		      proxy : {
			     type : 'zbusrpc',
			     module : 'SecViewRoleTreeFunctionService',
			     extraParams : {
			      funGroup : 'EXT'
			     },
			     reader : {
			      type : 'json'
			     }
		      },
		      listeners : {
			     scope : this,
			     beforeload : this.onTreePermissionStoreBeforeLoad
		      }
		     }),
		   listeners : {
		    scope : this,
		    select : this.onTreePermissionSelect
		   }
	    });

	  this.gridFunCtl = Ext.create('Ext.grid.Panel', {
		   height : 200,
		   title : T.label.controlList,
		   selModel : Ext.create('Ext.selection.CheckboxModel', {
		      checkOnly : true
		     }),
		   columns : [{
		      text : T.label.code,
		      dataIndex : 'funCode',
		      width : 70
		     }, {
		      text : T.label.controlName,
		      dataIndex : 'ctlName',
		      width : 70
		     }, {
		      text : T.label.controlDesc,
		      dataIndex : 'ctlDesc',
		      width : 150
		     }],
		   store : Ext.create('Ext.data.JsonStore', {
		      fields : ['funCode', 'ctlName', 'ctlDesc', 'hasCtl'],
		      proxy : {
			     type : 'zbusrpc',
			     module : 'SecViewRoleFunctionControlService',
			     reader : {
			      type : 'json',
			      root : 'roleFunCtlList'
			     }
		      },
		      listeners : {
			     scope : this,
			     load : this.onGridFunCtlStoreLoad
		      }
		     })
	    });

	  //功能菜单列表
	  this.gridFun = Ext.create('Ext.grid.Panel', {
		   title : T.label.moduleFunctionList,
		   flex : 1,
		   columns : [{
		      text : T.label.code,
		      dataIndex : 'funCode',
		      width : 80
		     }, {
		      text : T.label.desc + "1",
		      dataIndex : 'funDesc',
		      width : 120
		     }, {
		      text : T.label.desc + "2",
		      dataIndex : 'localeFunDesc',
		      width : 120
		     }, {
		      text : T.label.type,
		      dataIndex : 'funType',
		      width : 60,
		      renderer : function(value) {
			     return 'F' === value ? T.label.func : T.label.menu;
		      }
		     }, {
		      text : T.label.group,
		      dataIndex : 'funGroup',
		      width : 60,
		      renderer : function(value) {
			     if (value === 'QT') {
			      return 'Qt';
			     } else if (value === 'EXT') {
			      return 'Extjs';
			     }

			     return value;
		      }
		     }, {
		      text : T.label.clientSide,
		      dataIndex : 'funSide',
		      width : 60,
		      renderer : function(value) {
			     if (value === 'U') {
			      return T.label.func;
			     } else if (value === 'O') {
			      return T.label.operate;
			     } else if (value === 'C') {
			      return T.label.chart;
			     }

			     return value;
		      }
		     }],
		   store : Ext.create('Ext.data.JsonStore', {
		      fields : ['funCode', 'funDesc', 'localeFunDesc', 'funType', 'asmName', 'asmFile', 'funGroup', 'funSide'],
		      pageSize : 30,
		      proxy : {
			     type : 'zbusrpc',
			     module : 'BasViewModuleFunctionDefinitionService',
			     extraParams : {
			      funGroup : 'EXT'
			     },
			     reader : {
			      root : 'funDefList'
			     }
		      }
		     })
	    });
	  //菜单加入权限和权限移除、刷新操作按钮
	  this.btnAddSibling = Ext.create('Ext.button.Button', {
		   iconCls : 'icon-down-left',
		   tooltip : T.msg.add_item_as_sibling,
		   scope : this,
		   handler : this.onBtnAddSiblingClicked
	    });
	  this.btnAddChild = Ext.create('Ext.button.Button', {
		   iconCls : 'icon-left-down',
		   tooltip : T.msg.add_item_as_child,
		   scope : this,
		   handler : this.onBtnAddChildClicked
	    });
	  this.btnRemove = Ext.create('Ext.button.Button', {
		   iconCls : 'icon-delete',
		   tooltip : T.msg.remove_item_from_permission,
		   scope : this,
		   handler : this.onBtnRemoveClicked
	    });
	  this.btnRefresh = Ext.create('Ext.button.Button', {
		   iconCls : 'icon-refresh',
		   tooltip : T.msg.refresh_permission,
		   scope : this,
		   handler : this.onBtnRefreshClicked
	    });

	  //权限信息维护
	  this.cmbOrgCode = Ext.create('Ext.form.field.ComboBox', {
		   fieldLabel : T.label.organization,
		   labelWidth : 60,
		   valueField : 'key1',
		   displayField : 'data1',
		   editable : false,
		   allowBlank : false,
		   store : {
		    xtype : 'json',
		    fields : ['key1', 'data1'],
		    proxy : {
			   type : 'zbusrpc',
			   module : 'BasViewCommonDataSetupDetailService',
			   extraParams : {
			    groupName : 'ORG'
			   },
			   reader : {
			    root : 'cdsDtlList'
			   }
		    }
		   }
	    });
	  this.txtRoleCode = Ext.create('Ext.form.field.Text', {
		   fieldLabel : T.label.roleCode,
		   maxLength : 20,
		   labelWidth : 60,
		   allowBlank : false
	    });
	  this.txtRoleName = Ext.create('Ext.form.field.Text', {
		   fieldLabel : T.label.roleName,
		   labelWidth : 60,
		   maxLength : 50
	    });
	  this.cmbStatus = Ext.create('Ext.form.field.ComboBox', {
		   fieldLabel : T.label.status,
		   labelWidth : 60,
		   valueField : 'value',
		   displayField : 'text',
		   editable : false,
		   value : 'Y',
		   store : {
		    xtype : 'array',
		    fields : ['value', 'text'],
		    data : [['Y', T.label.valid], ['N', T.label.invalid]]
		   }
	    });

	  this.btnSaveRole = Ext.create('Ext.button.Button', {
		   text : T.label.saveRole,
		   itemId : 'btnSaveRole',
		   scope : this,
		   handler : this.onBtnSaveRoleClicked
	    });
	  this.btnSavePermission = Ext.create('Ext.button.Button', {
		   text : T.label.savePermission,
		   scope : this,
		   itemId : 'btnSavePermission',
		   handler : this.onBtnSavePermissionClicked
	    });
	  this.btnSaveControl = Ext.create('Ext.button.Button', {
		   text : T.label.saveControl,
		   scope : this,
		   itemId : 'btnSaveControl',
		   handler : this.onBtnSaveControlClicked
	    });

	  this.gridRole = Ext.create('Ext.grid.Panel', {
		   title : T.label.Role,
		   flex : 1,
		   columns : [{
		      text : T.label.organization,
		      dataIndex : 'orgCode',
		      width : 80
		     }, {
		      text : T.label.roleCode,
		      dataIndex : 'secRoleCode',
		      width : 80
		     }, {
		      text : T.label.roleName,
		      dataIndex : 'secRoleName'
		     }, {
		      text : T.label.valid,
		      dataIndex : 'isValid'
		     }],
		   store : {
		    xtype : 'json',
		    autoLoad : true,
		    fields : ['orgCode', 'secRoleCode', 'secRoleName', 'isValid'],
		    proxy : {
			   type : 'zbusrpc',
			   module : 'SecViewSecurityRoleListService',
			   reader : {
			    root : 'roleList'
			   }
		    }
		   },
		   listeners : {
		    scope : this,
		    select : this.onGridRoleSelect
		   }
	    });

	  this.items = [{//中间左侧权限菜单树
		 xtype : 'panel',
		 flex : 2,
		 layout : {
		  type : 'vbox',
		  align : 'stretch'
		 },
		 items : [this.cmbFunSide, this.treePermission, this.gridFunCtl]
	  }, {//中间权限操作工具栏
		   xtype : 'toolbar',
		   vertical : true,
		   layout : {
		    type : 'vbox',
		    pack : 'center'
		   },
		   items : [this.btnAddSibling, this.btnAddChild, this.btnRemove, this.btnRefresh]
	    }, {//中间右侧菜单功能清单
		   xtype : 'panel',
		   flex : 3,
		   layout : {
		    type : 'vbox',
		    align : 'stretch'
		   },
		   items : [this.gridFun, {
		      xtype : 'pagingtoolbar',
		      displayInfo : true,
		      store : this.gridFun.getStore()
		     }]
	    }, {//最右侧角色信息维护和清单
		   xtype : 'form',
		   width : 260,
		   layout : {
		    type : 'vbox',
		    align : 'stretch'
		   },
		   items : [{
		      xtype : 'fieldset',
		      title : T.label.Operate,
		      defaults : {
			     anchor : '98%'
		      },
		      items : [this.cmbOrgCode, this.txtRoleCode, this.txtRoleName]
		     }, this.gridRole, {
		      xtype : 'toolbar',
		      items : [this.btnSaveRole, '-', this.btnSavePermission, '-', this.btnSaveControl]
		     }]
	    }];

	  //this.treePermission.getStore().on('beforeload', this.onTreePermissionStoreBeforeLoad, this);
	  this.treePermission.getStore().on('load', this.onTreePermissionStoreLoad, this);

	  this.callParent();
	 },
	 onTreePermissionSelect : function(rm, record) {
	  var roleRcds = this.gridRole.getSelectionModel().getSelection();
	  if (Ext.isEmpty(roleRcds) || Ext.isEmpty(record.get('funCode'))) {
		 return;
	  }

	  this.gridFunCtl.getStore().load({
		   params : {
		    roleOrgCode : roleRcds[0].get('orgCode'),
		    roleCode : roleRcds[0].get('secRoleCode'),
		    funCode : record.get('funCode'),
		    hasCtl : 'Y'
		   }
	    });
	 },
	 onBtnAddSiblingClicked : function(btn) {
	  //添加菜单或功能项作为所选节点兄弟
	  var permRcds = this.treePermission.getSelectionModel().getSelection();
	  var funRcds = this.gridFun.getSelectionModel().getSelection();
	  if (!Ext.isEmpty(permRcds) && !Ext.isEmpty(funRcds) && permRcds[0].parentNode != null) {
		 //查找权限树的所有节点
		 var treeNodes = this.findPermissionChild(this.treePermission.getRootNode());
		 if (!Ext.isEmpty(treeNodes)) {
		  //判断正在添加的是否重复
		  var isExists = false;
		  Ext.each(treeNodes, function(node) {
			   if (node.funCode === funRcds[0].get('funCode')) {
			    isExists = true;
			    return false;
			   }
		    });

		  if (isExists) {
			 Ext.Msg.show({
			    title : T.label.error,
			    msg : T.msg.the_data_has_already_existed,
			    icon : Ext.Msg.ERROR,
			    buttons : Ext.Msg.OK
			   });

			 return;
		  }
		 }

		 //添加
		 permRcds[0].parentNode.appendChild(permRcds[0].createNode({
		    funCode : funRcds[0].get('funCode'),
		    parentFunCode : permRcds[0].parentNode.get('funCode'),
		    funType : funRcds[0].get('funType'),
		    leaf : funRcds[0].get('funType') === 'F',
		    text : '[' + funRcds[0].get('funCode') + '] ' + funRcds[0].get('localeFunDesc')
		   }));
		 permRcds[0].parentNode.expand();
	  }
	 },
	 onBtnAddChildClicked : function(btn) {
	  var permRcds = this.treePermission.getSelectionModel().getSelection();
	  var funRcds = this.gridFun.getSelectionModel().getSelection();
	  if (!Ext.isEmpty(permRcds) && !Ext.isEmpty(funRcds)
	    && (permRcds[0].get('funType') === 'M' || Ext.isEmpty(permRcds[0].get('funCode')))) {
		 var treeNodes = this.findPermissionChild(this.treePermission.getRootNode());
		 if (!Ext.isEmpty(treeNodes)) {
		  var isExists = false;
		  Ext.each(treeNodes, function(node) {
			   if (node.funCode === funRcds[0].get('funCode')) {
			    isExists = true;
			    return false;
			   }
		    });

		  if (isExists) {
			 Ext.Msg.show({
			    title : T.label.error,
			    msg : T.msg.the_data_has_already_existed,
			    icon : Ext.Msg.ERROR,
			    buttons : Ext.Msg.OK
			   });

			 return;
		  }
		 }

		 permRcds[0].appendChild(permRcds[0].createNode({
		    funCode : funRcds[0].get('funCode'),
		    parentFunCode : permRcds[0].get('funCode'),
		    funType : funRcds[0].get('funType'),
		    leaf : funRcds[0].get('funType') === 'F',
		    text : '[' + funRcds[0].get('funCode') + '] ' + funRcds[0].get('localeFunDesc')
		   }));
		 permRcds[0].expand();
	  }
	 },
	 onBtnRemoveClicked : function(btn) {
	  var permRcds = this.treePermission.getSelectionModel().getSelection();
	  if (!Ext.isEmpty(permRcds) && !Ext.isEmpty(permRcds[0].get('funCode'))) {
		 permRcds[0].parentNode.removeChild(permRcds[0]);
	  }
	 },
	 onBtnRefreshClicked : function(btn) {
	  this.loadPermission();
	 },
	 onBtnSaveRoleClicked : function(btn) {
	  if (this.cmbOrgCode.isValid() && this.txtRoleCode.isValid()) {
		 Ext.Msg.show({
		    title : T.label.save,
		    msg : T.msg.are_you_sure_to_save_data,
		    icon : Ext.Msg.QUESTION,
		    buttons : Ext.Msg.YESNO,
		    scope : this,
		    fn : function(btnId) {
			   if (btnId == 'yes') {
			    btn.disable();
			    this.saveRole(btn);
			   }
		    }
		   });
	  }
	 },
	 saveRole : function(btn) {
	  YX.ZbusRpc.request({
		   module : 'SecSaveRoleDefinitionService',
		   scope : this,
		   showSuccess : true,
		   params : {
		    orgCode : this.cmbOrgCode.getValue(),
		    secRoleCode : this.txtRoleCode.getValue(),
		    secRoleName : this.txtRoleName.getValue(),
		    isValid : this.cmbStatus.getValue()
		   },
		   callback : function() {
		    btn.enable();
		   },
		   success : function() {
		    this.gridRole.getStore().reload();
		   }
	    });
	 },
	 onBtnSavePermissionClicked : function(btn) {
	  var roleRcds = this.gridRole.getSelectionModel().getSelection();
	  if (this.treePermission.getRootNode().hasChildNodes() && !Ext.isEmpty(roleRcds)) {
		 Ext.Msg.show({
		    title : T.label.save,
		    msg : T.msg.are_you_sure_to_save_data,
		    icon : Ext.Msg.QUESTION,
		    buttons : Ext.Msg.YESNO,
		    scope : this,
		    fn : function(btnId) {
			   if (btnId == 'yes') {
			    btn.disable();
			    this.savePermission(btn);
			   }
		    }
		   });
	  }
	 },
	 savePermission : function(btn) {
	  var roleRcds = this.gridRole.getSelectionModel().getSelection();
	  var rootNode = this.treePermission.getRootNode();
	  var roleList = this.findPermissionChild(rootNode);
	  for (var i = 0; i < roleList.length; i++) {
		 roleList[i].seqNum = i + 1;
	  }

	  YX.ZbusRpc.request({
		   module : 'SecSaveRolePermissionService',
		   scope : this,
		   showSuccess : true,
		   params : {
		    roleOrgCode : roleRcds[0].get('orgCode'),
		    roleGroupCode : roleRcds[0].get('secRoleCode'),
		    roleFunList : roleList
		   },
		   callback : function() {
		    btn.enable();
		   },
		   success : function() {
		    this.treePermission.getStore().reload();
		   }
	    });
	 },
	 findPermissionChild : function(node) {
	  var child = [];
	  if (node && node.hasChildNodes()) {
		 node.eachChild(function(childNode) {
		    child.push({
			     funCode : childNode.get('funCode'),
			     parentFunCode : node.get('funCode')
		      });

		    var childNodes = this.findPermissionChild(childNode);
		    if (!Ext.isEmpty(childNodes)) {
			   Ext.each(childNodes, function(childNode) {
			      child.push(childNode);
			     });
		    }
		   }, this);
	  }

	  return child;
	 },
	 onBtnSaveControlClicked : function(btn) {
	  var roleRcds = this.gridRole.getSelectionModel().getSelection();
	  var ctlRcds = this.gridFunCtl.getSelectionModel().getSelection();
	  if (!Ext.isEmpty(roleRcds) && !Ext.isEmpty(ctlRcds)) {
		 Ext.Msg.show({
		    title : T.label.save,
		    msg : T.msg.are_you_sure_to_save_data,
		    icon : Ext.Msg.QUESTION,
		    buttons : Ext.Msg.YESNO,
		    scope : this,
		    fn : function(btnId) {
			   if (btnId == 'yes') {
			    btn.disable();
			    this.saveControl(btn);
			   }
		    }
		   });
	  }
	 },
	 saveControl : function(btn) {
	  var roleRcds = this.gridRole.getSelectionModel().getSelection();
	  var ctlRcds = this.gridFunCtl.getSelectionModel().getSelection();
	  var ctlList = [];
	  Ext.each(ctlRcds, function(rcd) {
		   ctlList.push({
		      orgCode : roleRcds[0].get('orgCode'),
		      roleCode : roleRcds[0].get('secRoleCode'),
		      funCode : rcd.get('funCode'),
		      ctlName : rcd.get('ctlName')
		     });
	    });

	  YX.ZbusRpc.request({
		   module : 'SecSaveRoleControlService',
		   scope : this,
		   showSuccess : true,
		   params : {
		    ctlList : ctlList
		   },
		   callback : function() {
		    btn.enable();
		   }
	    });
	 },
	 onCmbFunSideSelect : function(field, records) {
	  this.loadPermission();
	  this.loadFunction();
	 },
	 loadPermission : function() {
	  var roleRcds = this.gridRole.getSelectionModel().getSelection();
	  if (Ext.isEmpty(roleRcds)) {
		 return;
	  }

	  var fs = this.cmbFunSide.getValue();
	  this.treePermission.getStore().load({
		   params : {
		    secOrgCode : roleRcds[0].get('orgCode'),
		    secRoleCode : roleRcds[0].get('secRoleCode'),
		    funSide : fs
		   }
	    });

	  if (this.gridFunCtl.getStore().getCount() > 0) {
		 this.gridFunCtl.getStore().removeAll();
	  }
	 },
	 onGridRoleSelect : function() {
	  this.loadPermission();
	 },
	 loadFunction : function() {
	  var fs = this.cmbFunSide.getValue();
	  this.gridFun.getStore().getProxy().setExtraParam('funSide', fs);
	  this.gridFun.getStore().loadPage(1);
	 },
	 onTreePermissionStoreBeforeLoad : function(store, operation) {
	  if (Ext.isEmpty(operation.params)
	    || (Ext.isEmpty(operation.params.funSide) && Ext.isEmpty(operation.params.funGroup))) {
		 if (store.getCount() > 0) {
		  store.removeAll();
		 }
		 return false;
	  }

	  return true;
	 },
	 onTreePermissionStoreLoad : function(store, node, records, successful) {
	  if (successful && !Ext.isEmpty(records)) {
		 var roleRcds = this.gridRole.getSelectionModel().getSelection();
		 if (!Ext.isEmpty(roleRcds)) {
		  Ext.each(records, function(rcd) {
			   rcd.set('roleCode', roleRcds[0].get('secRoleCode'));
		    });
		 }

		 this.treePermission.expandAll();
	  }

	  if (this.gridFunCtl.getStore().getCount() > 0) {
		 this.gridFunCtl.getStore().removeAll();
	  }
	 },
	 onGridFunCtlStoreLoad : function(store, records, successful) {
	  if (!successful) {
		 return;
	  }

	  var selRcds = [];
	  Ext.each(records, function(rcd) {
		   if ('Y' === rcd.get('hasCtl')) {
		    selRcds.push(rcd);
		   }
	    });
	  this.gridFunCtl.getSelectionModel().select(selRcds, true, true);
	 }
  });